from django.shortcuts import render, HttpResponse, redirect
from app01.utils.pagination import Pagination
# Create your views here.
from app01 import models
from app01.utils.form import PrettyModelFrom, PrettyEditModelFrom
"""靓号列表"""


def pretty_list(request):
    # # < QuerySet[ < PrettyNum: PrettyNumobject(7) >] >
    # q1 =models.PrettyNum.objects.filter(mobile="13782072361",id=7)
    # print(q1)
    # # filter可以通过传字典的方式
    # data_dict={"mobile":"13782072361","id":7}
    # q2 = models.PrettyNum.objects.filter(**data_dict)
    # print(q2)
    # select * from 表 order by level desc;
    data_dict = {}
    search_data = request.GET.get("q", "")
    if search_data:
        data_dict["mobile__contains"] = search_data
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request, queryset)
    context = {
        "page_queryset": page_object.page_queryset, "search_data": search_data, "page_string": page_object.html()
    }

    # # 根据用户想要访问的页码，计算出起止位置
    # page = int(request.GET.get("page", 1))
    # page_size = 10
    # # start = (page - 1) * page_size
    # # end = page * page_size
    # # 数据总条数
    # total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()
    # # 总页码
    # total_page_count, div = divmod(total_count, page_size)
    # if div:
    #     total_page_count += 1
    # # 计算出，显示当前页的前5页和后5页
    # plus = 5
    return render(request, "pretty_list.html", context)


def pretty_add(request):
    if request.method == "GET":
        form = PrettyModelFrom
        return render(request, "pretty_add.html", {"form": form})
    form = PrettyModelFrom(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, "pretty_add.html", {"form": form})


"""编辑靓号"""


def pretty_edit(request, nid):
    row_object = models.PrettyNum.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据
        form = PrettyEditModelFrom(instance=row_object)
        return render(request, "pretty_edit.html", {"form": form})
    form = PrettyEditModelFrom(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据
        # form.instance.字段名 = 值
        form.save()
        return redirect("/pretty/list/")
    return render(request, "pretty_edit.html", {"form": form})


"""删除靓号"""


def pretty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")
